const vscode = require('vscode');
const path = require('path');
const fs = require('fs');
const net = require('net');

// 全局变量
let chatPanel = null;
let mcpReady = false;
let currentTriggerData = null;
let pendingMcpSessions = new Map(); // 存储待处理的MCP会话

// IPC配置
const IPC_PIPE_NAME = process.platform === 'win32' 
    ? `\\\\.\\pipe\\review_gate_v3_${process.pid}`
    : `/tmp/review_gate_v3_${process.pid}.sock`;



// IPC服务器管理器 - Extension监听MCP服务器的连接
class ExtensionIPCServer {
    constructor(context) {
        this.context = context;
        this.server = null;
        this.connections = new Set();
    }

    async start() {
        try {
            // 清理可能存在的旧管道文件
            if (process.platform !== 'win32' && fs.existsSync(IPC_PIPE_NAME)) {
                fs.unlinkSync(IPC_PIPE_NAME);
            }

            this.server = net.createServer((socket) => {
                this.connections.add(socket);
                logMessage(`🔗 MCP服务器已连接到Extension`);

                socket.on('data', (data) => {
                    try {
                        const message = JSON.parse(data.toString());
                        this.handleIPCMessage(message, socket);
                    } catch (error) {
                        logMessage(`❌ IPC消息解析错误: ${error.message}`);
                    }
                });

                socket.on('close', () => {
                    this.connections.delete(socket);
                    logMessage(`🔌 MCP服务器连接已关闭`);
                });

                socket.on('error', (error) => {
                    this.connections.delete(socket);
                    logMessage(`❌ IPC连接错误: ${error.message}`);
                });
            });

            this.server.listen(IPC_PIPE_NAME, () => {
                logMessage(`🚀 Extension IPC服务器启动: ${IPC_PIPE_NAME}`);
                logMessage(`📝 Socket文件已创建，PID: ${process.pid}`);
            });

        } catch (error) {
            logMessage(`❌ Extension IPC服务器启动失败: ${error.message}`);
            throw error;
        }
    }

    handleIPCMessage(message, socket) {
        const { type, id, data } = message;
        logMessage(`📨 收到MCP消息: ${type}`);

        switch (type) {
            case 'request_user_input':
                this.handleUserInputRequest(data, socket, id);
                break;

            case 'ping':
                this.sendResponse(socket, id, { type: 'pong', timestamp: Date.now() });
                break;

            default:
                logMessage(`⚠️ 未知MCP消息类型: ${type}`);
        }
    }

    async handleUserInputRequest(data, socket, requestId) {
        // 存储MCP会话信息，即使弹窗关闭也保持
        pendingMcpSessions.set(requestId, {
            data: { ...data },
            socket: socket,
            request_id: requestId,
            timestamp: Date.now(),
            status: 'pending'
        });

        currentTriggerData = { ...data, request_id: requestId, socket: socket };

        const options = {
            message: data.message || "请提供您的审核或反馈：",
            title: data.title || "Review Gate V3",
            autoFocus: true,
            toolData: data,
            mcpIntegration: true,
            triggerId: requestId,
            embeddedMode: true
        };

        logMessage(`📨 收到MCP用户输入请求: ${requestId}`);
        logMessage(`📋 请求内容: ${data.message || 'default message'}`);
        logMessage(`💾 会话已保存到持久存储: ${requestId}`);
        
        openReviewGatePopup(this.context, options);
    }

    sendResponse(socket, requestId, data) {
        try {
            const response = {
                type: 'response',
                id: requestId,
                data: data,
                timestamp: Date.now()
            };
            socket.write(JSON.stringify(response) + '\n');
            logMessage(`📤 响应已发送: ${requestId}`);
        } catch (error) {
            logMessage(`❌ 发送响应失败: ${error.message}`);
        }
    }

    sendUserResponse(requestId, userInput, attachments = []) {
        // 优先从持久会话存储中查找
        let targetSocket = null;
        let sessionData = null;
        
        if (requestId && pendingMcpSessions.has(requestId)) {
            sessionData = pendingMcpSessions.get(requestId);
            targetSocket = sessionData.socket;
            logMessage(`🔍 从持久存储中找到会话: ${requestId}`);
        } else if (currentTriggerData?.socket) {
            // 备用方案：从当前触发器数据获取
            targetSocket = currentTriggerData.socket;
            logMessage(`🔍 从当前触发器数据获取socket: ${currentTriggerData.request_id}`);
        } else {
            // 最后备用方案：使用第一个可用的连接
            for (const socket of this.connections) {
                if (socket && !socket.destroyed) {
                    targetSocket = socket;
                    logMessage(`🔍 使用第一个可用连接作为备用方案`);
                    break;
                }
            }
        }
        
        if (targetSocket && requestId) {
            // 格式化附件数据，确保图片正确传递给MCP服务器（字段名匹配）
            const formattedAttachments = attachments.map(attachment => {
                let base64Data = attachment.data || attachment;
                let mimeType = 'image/png';
                
                // 解析data URL获取MIME类型和Base64数据
                if (base64Data && base64Data.startsWith('data:')) {
                    const parts = base64Data.split(',');
                    if (parts.length === 2) {
                        const header = parts[0]; // "data:image/png;base64"
                        mimeType = header.split(';')[0].replace('data:', ''); // "image/png"
                        base64Data = parts[1]; // 纯Base64数据，不含header
                    }
                }
                
                return {
                    type: attachment.type || 'image',
                    fileName: attachment.name || 'image.png',  // MCP期望fileName
                    base64Data: base64Data,                     // MCP期望base64Data
                    mimeType: mimeType,                         // MCP期望mimeType
                    size: attachment.size || 0
                };
            });
            
            this.sendResponse(targetSocket, requestId, {
                user_input: userInput,
                attachments: formattedAttachments,
                timestamp: Date.now(),
                extension_pid: process.pid  // 使用PID而不是extension_id
            });
            
            // 标记会话为已完成并清理
            if (requestId && pendingMcpSessions.has(requestId)) {
                pendingMcpSessions.get(requestId).status = 'completed';
                logMessage(`✅ 会话已完成: ${requestId}`);
                // 可选：延迟清理会话数据（以防需要重试）
                setTimeout(() => {
                    pendingMcpSessions.delete(requestId);
                    logMessage(`🧹 会话数据已清理: ${requestId}`);
                }, 5000);
            }
            
            logMessage(`📤 用户响应已通过IPC发送: ${requestId} (connections: ${this.connections.size}, attachments: ${formattedAttachments.length})`);
        } else {
            logMessage(`⚠️ 无法发送用户响应 - socket: ${!!targetSocket}, requestId: ${requestId}, connections: ${this.connections.size}`);
            logMessage(`⚠️ 会话存储状态: ${pendingMcpSessions.size} 个待处理会话`);
            for (const [id, session] of pendingMcpSessions.entries()) {
                logMessage(`   - ${id}: ${session.status}, socket: ${!!session.socket}`);
            }
        }
    }

    stop() {
        // 关闭所有连接
        for (const socket of this.connections) {
            socket.destroy();
        }
        this.connections.clear();

        if (this.server) {
            this.server.close();
            this.server = null;
        }

        // 清理管道文件
        if (process.platform !== 'win32' && fs.existsSync(IPC_PIPE_NAME)) {
            try {
                fs.unlinkSync(IPC_PIPE_NAME);
            } catch (error) {
                // 忽略清理错误
            }
        }

        logMessage('🛑 Extension IPC服务器已停止');
    }
}

// 全局IPC服务器实例
let ipcServer = null;

// 国际化支持
function getLocalizedText(key) {
    const texts = {
        'extension.activated': 'Review Gate V3扩展现在在Cursor中活跃，支持IPC通信！',
        'extension.activatedLog': 'Review Gate V3扩展已激活，支持IPC通信，由k1234567开发',
        'chat.welcome': '欢迎使用Review Gate V3！请提供您的审核或反馈。',
        'chat.title': 'Review Gate',
        'responses.sent1': '审核已发送 - 紧握您的裤子直到审核门再次被调用！🎢',
        'responses.sent2': '消息已传递！Agent可能正在做agent的事情...⚡',
        'responses.sent3': '您的智慧已传输给数字霸主！🤖',
        'responses.sent4': '响应已发射到虚空 - 期待即将到来的agent魔法！✨',
        'responses.sent5': '审核门已关闭 - Agent正在咀嚼您的输入！🍕',
        'mcp.active': 'MCP活跃',
        'mcp.inactive': 'MCP非活跃',
        'placeholder.enterMessage': '输入您的审核或反馈 (支持粘贴图片)...',
        'placeholder.agentWaiting': 'Cursor Agent正在等待您的响应...',
        'button.uploadImage': '上传图片',
        'button.sendReview': '发送审核',
        'button.sendResponse': '响应给Agent',
        'author.info': 'by k1234567'
    };
    
    return texts[key] || key;
}

function logMessage(message) {
    const timestamp = new Date().toISOString();
    const logMsg = `[${timestamp}] ${message}`;
    console.log(logMsg);
}

function activate(context) {
    console.log('Review Gate V3 IPC通信扩展现在在Cursor中活跃！');
    
    logMessage('Review Gate V3 IPC通信扩展已激活');

    // 注册命令 - 支持MCP会话恢复
    let openChatCmd = vscode.commands.registerCommand('reviewGate.openChat', () => {
        // 检查是否有待处理的MCP会话
        if (pendingMcpSessions.size > 0) {
            const activeSessions = Array.from(pendingMcpSessions.entries())
                .filter(([id, session]) => session.status === 'pending');
            
            if (activeSessions.length > 0) {
                const [latestId, latestSession] = activeSessions[activeSessions.length - 1];
                logMessage(`🔄 检测到待处理的MCP会话，自动恢复: ${latestId}`);
                
                const options = {
                    message: latestSession.data.message || "请提供您的审核或反馈：",
                    title: latestSession.data.title || "Review Gate V3 - MCP会话恢复",
                    autoFocus: true,
                    toolData: latestSession.data,
                    mcpIntegration: true,
                    triggerId: latestId,
                    embeddedMode: true
                };
                
                openReviewGatePopup(context, options);
                return;
            }
        }
        
        // 如果没有待处理的MCP会话，正常打开弹窗
        openReviewGatePopup(context, {
            message: getLocalizedText('chat.welcome'),
            title: 'Review Gate V3'
        });
    });

    let serverStatusCmd = vscode.commands.registerCommand('reviewGate.serverStatus', () => {
        const status = mcpReady ? 'MCP活跃' : 'MCP非活跃';
        const sessionInfo = pendingMcpSessions.size > 0 ? 
            `，${pendingMcpSessions.size} 个待处理MCP会话` : '，无待处理会话';
        vscode.window.showInformationMessage(`MCP状态: ${status}${sessionInfo}`);
    });

    context.subscriptions.push(openChatCmd, serverStatusCmd);

    // 初始化IPC架构
    initializeIPCArchitecture(context);
    
    logMessage(`Review Gate V3已激活！PID: ${process.pid}`);
}

async function initializeIPCArchitecture(context) {
    try {
        // 启动Extension IPC服务器
        ipcServer = new ExtensionIPCServer(context);
        await ipcServer.start();
        
        mcpReady = true;
        updateChatPanelStatus();
        
        logMessage('✅ IPC通信架构初始化完成');
        
    } catch (error) {
        logMessage(`❌ IPC通信架构初始化失败: ${error.message}`);
        mcpReady = false;
        updateChatPanelStatus();
        
        // 显示错误通知
        vscode.window.showErrorMessage(`Review Gate IPC服务启动失败: ${error.message}`);
    }
}

function updateChatPanelStatus() {
    if (chatPanel) {
        chatPanel.webview.postMessage({
            command: 'updateMcpStatus',
            active: mcpReady
        });
    }
}

function openReviewGatePopup(context, options = {}) {
            const {
            message = "欢迎使用Review Gate V3！请提供您的审核或反馈。",
            title = "Review Gate V3",
            autoFocus = false,
            toolData = null,
            mcpIntegration = false,
            triggerId = null
        } = options;
    
    // 改进的触发器数据设置逻辑
    if (triggerId) {
        // 优先从持久会话存储恢复数据
        if (pendingMcpSessions.has(triggerId)) {
            const sessionData = pendingMcpSessions.get(triggerId);
            currentTriggerData = { 
                ...sessionData.data, 
                request_id: triggerId, 
                socket: sessionData.socket 
            };
            logMessage(`🔄 从持久存储恢复会话数据: ${triggerId}`);
        } else {
            currentTriggerData = { ...toolData, request_id: triggerId };
            logMessage(`📝 设置新的触发器数据: ${triggerId}`);
        }
    }

    if (chatPanel) {
        chatPanel.reveal(vscode.ViewColumn.One);
        chatPanel.title = "Review Gate";
        
        if (mcpIntegration) {
            setTimeout(() => {
                chatPanel.webview.postMessage({
                    command: 'updateMcpStatus',
                    active: true
                });
            }, 100);
        }
        
        if (autoFocus) {
            setTimeout(() => {
                chatPanel.webview.postMessage({
                    command: 'focus'
                });
            }, 200);
        }
        
        return;
    }

    // 创建webview面板
    chatPanel = vscode.window.createWebviewPanel(
        'reviewGateChat',
        title,
        vscode.ViewColumn.One,
        {
            enableScripts: true,
            retainContextWhenHidden: true
        }
    );

    // 设置HTML内容
    chatPanel.webview.html = getReviewGateHTML(title, mcpIntegration);

    // 处理来自webview的消息
    chatPanel.webview.onDidReceiveMessage(
        async webviewMessage => {
            const currentTriggerId = (currentTriggerData && currentTriggerData.request_id) || triggerId;
            
            switch (webviewMessage.command) {
                case 'send':
                    logMessage(`用户输入: ${webviewMessage.text}`);
                    logMessage(`当前触发器ID: ${currentTriggerId}, MCP集成: ${mcpIntegration}, IPC服务器: ${!!ipcServer}`);
                    
                    // 立即禁用输入框，防止重复提交
                    if (chatPanel) {
                        chatPanel.webview.postMessage({
                            command: 'updateMcpStatus',
                            active: false
                        });
                    }
                    
                    // 如果是IPC模式，直接发送给MCP服务器
                    if (mcpIntegration && ipcServer && currentTriggerId) {
                        try {
                            ipcServer.sendUserResponse(
                                currentTriggerId, 
                                webviewMessage.text, 
                                webviewMessage.attachments || []
                            );
                            logMessage(`✅ 用户响应已发送到MCP服务器: ${currentTriggerId}`);
                        } catch (error) {
                            logMessage(`❌ 发送用户响应到MCP失败: ${error.message}`);
                        }
                    } else {
                        logMessage(`⚠️ 无法发送到MCP - 条件检查失败`);
                    }
                    
                    handleReviewMessage(webviewMessage.text, webviewMessage.attachments, currentTriggerId, mcpIntegration);
                    break;
                    
                case 'uploadImage':
                    handleImageUpload();
                    break;
                    
                case 'ready':
                    chatPanel.webview.postMessage({
                        command: 'updateMcpStatus',
                        active: mcpIntegration ? true : mcpReady
                    });
                    break;
            }
        },
        undefined,
        context.subscriptions
    );

    // 面板关闭时清理 - 但保留MCP会话数据
    chatPanel.onDidDispose(
        () => {
            const hadActiveMcpSession = currentTriggerData && currentTriggerData.request_id;
            
            chatPanel = null;
            currentTriggerData = null;
            
            // 重要改进：不再清理currentTriggerId，让MCP会话保持活跃
            if (hadActiveMcpSession) {
                logMessage(`🧹 弹窗关闭，但保留MCP会话: ${hadActiveMcpSession}`);
                logMessage(`💾 持久存储中有 ${pendingMcpSessions.size} 个会话`);
            } else {
                logMessage("🧹 弹窗关闭，已清理UI状态变量");
            }
        },
        null,
        context.subscriptions
    );

    if (autoFocus) {
        setTimeout(() => {
            chatPanel.webview.postMessage({
                command: 'focus'
            });
        }, 200);
    }
}

function getReviewGateHTML(title = "Review Gate", mcpIntegration = false) {
    return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${title}</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            font-family: var(--vscode-font-family);
            color: var(--vscode-foreground);
            background: var(--vscode-editor-background);
            margin: 0;
            padding: 0;
            height: 100vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        
        .review-container {
            height: 100vh;
            display: flex;
            flex-direction: column;
            max-width: 600px;
            margin: 0 auto;
            width: 100%;
            animation: slideIn 0.3s ease-out;
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .review-header {
            flex-shrink: 0;
            padding: 16px 20px 12px 20px;
            border-bottom: 1px solid var(--vscode-panel-border);
            display: flex;
            align-items: center;
            gap: 8px;
            background: var(--vscode-editor-background);
        }
        
        .review-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--vscode-foreground);
        }
        
        .review-author {
            font-size: 12px;
            opacity: 0.7;
            margin-left: auto;
        }
        
        .status-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: var(--vscode-charts-orange);
            animation: pulse 2s infinite;
            transition: background-color 0.3s ease;
            margin-right: 4px;
        }
        
        .status-indicator.active {
            background: var(--vscode-charts-green);
        }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        
        .messages-container {
            flex: 1;
            overflow-y: auto;
            padding: 16px 20px;
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        
        .message {
            display: flex;
            gap: 8px;
            animation: messageSlide 0.3s ease-out;
        }
        
        @keyframes messageSlide {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .message.user {
            justify-content: flex-end;
        }
        
        .message-bubble {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 18px;
            word-wrap: break-word;
            white-space: pre-wrap;
        }
        
        .message.system .message-bubble {
            background: var(--vscode-badge-background);
            color: var(--vscode-badge-foreground);
            border-bottom-left-radius: 6px;
        }
        
        .message.user .message-bubble {
            background: var(--vscode-button-background);
            color: var(--vscode-button-foreground);
            border-bottom-right-radius: 6px;
        }
        
        .input-container {
            flex-shrink: 0;
            display: flex;
            flex-direction: column;
            padding: 16px 20px 20px 20px;
            border-top: 1px solid var(--vscode-panel-border);
            background: var(--vscode-editor-background);
        }
        
        .input-container.disabled {
            opacity: 0.5;
            pointer-events: none;
        }
        
        .input-wrapper {
            flex: 1;
            display: flex;
            align-items: center;
            background: var(--vscode-input-background);
            border: 1px solid var(--vscode-input-border);
            border-radius: 20px;
            padding: 8px 12px;
            transition: all 0.2s ease;
            position: relative;
        }
        
        .input-wrapper:focus-within {
            border-color: transparent;
            box-shadow: 0 0 0 2px rgba(255, 165, 0, 0.4), 0 0 8px rgba(255, 165, 0, 0.2);
        }
        
        .message-input {
            flex: 1;
            background: transparent;
            border: none !important;
            outline: none !important;
            color: var(--vscode-input-foreground);
            resize: none;
            min-height: 20px;
            max-height: 120px;
            font-family: inherit;
            font-size: 14px;
            line-height: 1.4;
            padding-left: 24px;
        }
        
        .message-input::placeholder {
            color: var(--vscode-input-placeholderForeground);
        }
        
        .send-button {
            background: var(--vscode-button-background);
            color: var(--vscode-button-foreground);
            border: none;
            border-radius: 50%;
            width: 36px;
            height: 36px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            font-size: 14px;
            margin-left: 8px;
        }
        
        .send-button:hover {
            background: var(--vscode-button-hoverBackground);
            transform: scale(1.05);
        }
        
        .mcp-status {
            font-size: 11px;
            opacity: 0.6;
            margin-left: 4px;
        }
        
        .attach-button {
            background: transparent;
            border: none;
            color: var(--vscode-foreground);
            cursor: pointer;
            padding: 4px;
            border-radius: 4px;
            transition: all 0.2s ease;
            font-size: 14px;
            position: absolute;
            left: 4px;
            top: 50%;
            transform: translateY(-50%);
        }
        
        .attach-button:hover {
            background: var(--vscode-button-hoverBackground);
            color: var(--vscode-button-foreground);
        }
        
        .input-controls {
            display: flex;
            align-items: center;
            gap: 8px;
            width: 100%;
        }
        
        .image-preview-container {
            margin-bottom: 8px;
            display: none;
        }
        
        .image-preview-container.has-images {
            display: block;
        }
        
        .image-preview-list {
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
            padding: 4px 0;
        }
        
        .image-preview-item {
            position: relative;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 4px 8px;
            background: var(--vscode-badge-background);
            color: var(--vscode-badge-foreground);
            border-radius: 12px;
            font-size: 11px;
            border: 1px solid var(--vscode-input-border);
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .image-preview-item:hover {
            background: var(--vscode-button-hoverBackground);
            transform: translateY(-1px);
        }
        
        .image-preview-img {
            width: 16px;
            height: 16px;
            border-radius: 2px;
            object-fit: cover;
            flex-shrink: 0;
        }
        
        .image-preview-icon {
            font-size: 10px;
            opacity: 0.8;
            display: none; /* 隐藏图标，显示缩略图 */
        }
        
        .image-preview-name {
            max-width: 60px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .image-remove-btn {
            margin-left: 4px;
            width: 14px;
            height: 14px;
            background: transparent;
            color: var(--vscode-badge-foreground);
            border: none;
            border-radius: 50%;
            cursor: pointer;
            font-size: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            line-height: 1;
            opacity: 0.6;
            transition: opacity 0.2s;
        }
        
        .image-remove-btn:hover {
            opacity: 1;
            background: var(--vscode-errorForeground);
            color: white;
        }
        
        .message-images {
            margin-top: 12px;
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 8px;
            max-width: 100%;
        }
        
        .image-container {
            width: 100%;
            min-width: 150px;
            max-width: 200px;
            aspect-ratio: 16/9;
            border-radius: 8px;
            overflow: hidden;
            border: 1px solid var(--vscode-panel-border);
            transition: transform 0.2s ease;
        }
        
        .image-container:hover {
            transform: scale(1.02);
            border-color: var(--vscode-focusBorder);
        }
        
        .message-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
            cursor: pointer;
            transition: opacity 0.2s;
            display: block;
        }
        
        .message-image:hover {
            opacity: 0.95;
        }
        
        .image-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            z-index: 9999;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }
        
        .image-modal-content {
            position: relative;
            max-width: 90%;
            max-height: 90%;
            cursor: default;
        }
        
        .image-modal-img {
            width: 100%;
            height: auto;
            max-width: 80vw;
            max-height: 80vh;
            object-fit: contain;
            border-radius: 8px;
        }
        
        .image-modal-close {
            position: absolute;
            top: -30px;
            right: 0;
            font-size: 24px;
            color: white;
            cursor: pointer;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: rgba(0, 0, 0, 0.5);
            border-radius: 50%;
        }
        
        .image-modal-close:hover {
            background: rgba(0, 0, 0, 0.7);
        }
    </style>
</head>
<body>
    <div class="review-container">
        <div class="review-header">
            <div class="review-title">${title}</div>
            <div class="status-indicator" id="statusIndicator"></div>
            <div class="mcp-status" id="mcpStatus">IPC通信</div>
            <div class="review-author">${getLocalizedText('author.info')}</div>
        </div>
        
        <div class="messages-container" id="messages">
            <!-- 消息将添加到这里 -->
        </div>
        
        <div class="input-container" id="inputContainer">
            <div class="image-preview-container" id="imagePreviewContainer">
                <div class="image-preview-list" id="imagePreviewList">
                    <!-- 图片预览将添加到这里 -->
                </div>
            </div>
            <div class="input-controls">
                <div class="input-wrapper" id="inputWrapper">
                    <textarea id="messageInput" class="message-input" placeholder="${mcpIntegration ? getLocalizedText('placeholder.agentWaiting') : getLocalizedText('placeholder.enterMessage')}" rows="1"></textarea>
                    <button id="attachButton" class="attach-button" title="${getLocalizedText('button.uploadImage')}">
                        <i class="fas fa-image"></i>
                    </button>
                </div>
                <button id="sendButton" class="send-button" title="${mcpIntegration ? getLocalizedText('button.sendResponse') : getLocalizedText('button.sendReview')}">
                    <i class="fas fa-arrow-up"></i>
                </button>
            </div>
        </div>
    </div>

    <script>
        const vscode = acquireVsCodeApi();
        
        const messagesContainer = document.getElementById('messages');
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        const statusIndicator = document.getElementById('statusIndicator');
        const mcpStatus = document.getElementById('mcpStatus');
        const inputContainer = document.getElementById('inputContainer');
        const attachButton = document.getElementById('attachButton');
        const imagePreviewContainer = document.getElementById('imagePreviewContainer');
        const imagePreviewList = document.getElementById('imagePreviewList');
        
        let mcpActive = true;
        let mcpIntegration = ${mcpIntegration};
        let attachedImages = [];
        
        function updateMcpStatus(active) {
            mcpActive = active;
            
            if (active) {
                statusIndicator.classList.add('active');
                mcpStatus.textContent = '${getLocalizedText('mcp.active')}';
                inputContainer.classList.remove('disabled');
                messageInput.disabled = false;
                sendButton.disabled = false;
                messageInput.placeholder = mcpIntegration ? '${getLocalizedText('placeholder.agentWaiting')}' : '${getLocalizedText('placeholder.enterMessage')}';
            } else {
                statusIndicator.classList.remove('active');
                mcpStatus.textContent = '${getLocalizedText('mcp.inactive')}';
                inputContainer.classList.add('disabled');
                messageInput.disabled = true;
                sendButton.disabled = true;
                messageInput.placeholder = 'IPC服务不可用';
            }
        }
        
        function addMessage(text, type = 'user', attachments = []) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message ' + type;
            
            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-bubble';
            
            // 添加文本内容
            if (text.trim()) {
                const textDiv = document.createElement('div');
                textDiv.textContent = text;
                contentDiv.appendChild(textDiv);
            }
            
            // 添加图片附件
            if (attachments && attachments.length > 0) {
                const imagesDiv = document.createElement('div');
                imagesDiv.className = 'message-images';
                
                // 根据图片数量调整布局
                if (attachments.length === 1) {
                    imagesDiv.style.gridTemplateColumns = '1fr';
                    imagesDiv.style.maxWidth = '300px';
                } else if (attachments.length === 2) {
                    imagesDiv.style.gridTemplateColumns = 'repeat(2, 1fr)';
                }  else {
                    imagesDiv.style.gridTemplateColumns = 'repeat(auto-fit, minmax(140px, 1fr))';
                }
                
                attachments.forEach((attachment, index) => {
                    if (attachment.type === 'image') {
                        const imgContainer = document.createElement('div');
                        imgContainer.className = 'image-container';
                        
                        const img = document.createElement('img');
                        img.src = attachment.data;
                        img.alt = attachment.name || ('图片 ' + (index + 1));
                        img.className = 'message-image';
                        img.onclick = () => openImageModal(attachment.data);
                        
                        imgContainer.appendChild(img);
                        imagesDiv.appendChild(imgContainer);
                    }
                });
                
                contentDiv.appendChild(imagesDiv);
            }
            
            messageDiv.appendChild(contentDiv);
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }
        
        function openImageModal(src) {
            const modal = document.createElement('div');
            modal.className = 'image-modal';
            modal.innerHTML = 
                '<div class="image-modal-content">' +
                    '<span class="image-modal-close" onclick="this.parentElement.parentElement.remove()">&times;</span>' +
                    '<img src="' + src + '" class="image-modal-img">' +
                '</div>';
            document.body.appendChild(modal);
            
            modal.onclick = (e) => {
                if (e.target === modal) {
                    modal.remove();
                }
            };
        }
        

        
        function addImagePreview(file, dataUrl) {
            const previewItem = document.createElement('div');
            previewItem.className = 'image-preview-item';
            previewItem.onclick = () => openImageModal(dataUrl);
            
            // 添加缩略图
            const img = document.createElement('img');
            img.src = dataUrl;
            img.className = 'image-preview-img';
            
            // 添加文件名（简化显示）
            const fileName = document.createElement('span');
            fileName.className = 'image-preview-name';
            fileName.textContent = 'image';
            
            // 添加删除按钮
            const removeBtn = document.createElement('button');
            removeBtn.className = 'image-remove-btn';
            removeBtn.innerHTML = '×';
            removeBtn.onclick = (e) => {
                e.stopPropagation();
                removeImage(file.name);
            };
            
            previewItem.appendChild(img);
            previewItem.appendChild(fileName);
            previewItem.appendChild(removeBtn);
            imagePreviewList.appendChild(previewItem);
            
            updateImagePreviewVisibility();
        }
        
        function removeImage(fileName) {
            attachedImages = attachedImages.filter(img => img.name !== fileName);
            refreshImagePreviews();
        }
        
        function refreshImagePreviews() {
            imagePreviewList.innerHTML = '';
            attachedImages.forEach((img) => {
                addImagePreview({ name: img.name }, img.data);
            });
            updateImagePreviewVisibility();
        }
        
        function updateImagePreviewVisibility() {
            if (attachedImages.length > 0) {
                imagePreviewContainer.classList.add('has-images');
            } else {
                imagePreviewContainer.classList.remove('has-images');
            }
        }
        
        function handleFileSelect(files) {
            const MAX_IMAGES = 10;
            const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
            
            // 检查当前已有图片数量
            if (attachedImages.length >= MAX_IMAGES) {

                return;
            }
            
            Array.from(files).forEach(file => {
                if (file.type.startsWith('image/')) {
                    // 检查文件大小
                    if (file.size > MAX_FILE_SIZE) {
                   
                        return;
                    }
                    
                    // 检查数量限制
                    if (attachedImages.length >= MAX_IMAGES) {
                        return;
                    }
                    
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        // 为每次粘贴生成唯一的名称
                        const timestamp = Date.now();
                        const uniqueName = file.name.includes('.') 
                            ? file.name.replace(/(\.[^.]+)$/, '_' + timestamp + '$1')
                            : file.name + '_' + timestamp;
                        
                        const imageData = {
                            type: 'image',
                            name: uniqueName,
                            data: e.target.result,
                            size: file.size,
                            originalName: file.name
                        };
                        attachedImages.push(imageData);
                        addImagePreview({ name: uniqueName }, e.target.result);
                        
                    };
                    reader.readAsDataURL(file);
                }
            });
        }
        
        function sendMessage() {
            const text = messageInput.value.trim();
            if (!text && attachedImages.length === 0) return;
            
            // 发送前禁用输入界面，防止重复提交
            updateMcpStatus(false);
            
            addMessage(text, 'user', attachedImages);
            
            vscode.postMessage({
                command: 'send',
                text: text,
                attachments: attachedImages,
                timestamp: new Date().toISOString(),
                mcpIntegration: mcpIntegration
            });
            
            messageInput.value = '';
            attachedImages = [];
            refreshImagePreviews();
            adjustTextareaHeight();
        }
        
        function adjustTextareaHeight() {
            messageInput.style.height = 'auto';
            messageInput.style.height = Math.min(messageInput.scrollHeight, 120) + 'px';
        }
        
        // 事件监听器
        messageInput.addEventListener('input', adjustTextareaHeight);
        
        messageInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
        
        sendButton.addEventListener('click', sendMessage);
        
        // 图片上传事件监听器
        attachButton.addEventListener('click', () => {
            vscode.postMessage({ command: 'uploadImage' });
        });
        
        // 拖放和粘贴图片处理
        messageInput.addEventListener('paste', (e) => {
            const items = e.clipboardData.items;
            for (let i = 0; i < items.length; i++) {
                if (items[i].type.indexOf('image') !== -1) {
                    const file = items[i].getAsFile();
                    handleFileSelect([file]);
                    e.preventDefault();
                }
            }
        });
        
        // 拖拽上传
        document.addEventListener('dragover', (e) => {
            e.preventDefault();
        });
        
        document.addEventListener('drop', (e) => {
            e.preventDefault();
            if (e.dataTransfer.files.length > 0) {
                handleFileSelect(e.dataTransfer.files);
            }
        });
        
        // 处理来自扩展的消息
        window.addEventListener('message', event => {
            const message = event.data;
            
            switch (message.command) {
                case 'focus':
                    messageInput.focus();
                    break;
                case 'updateMcpStatus':
                    updateMcpStatus(message.active);
                    break;
                case 'addMessage':
                    addMessage(message.text, message.type || 'system');
                    break;
                case 'addImages':
                    if (message.images && message.images.length > 0) {
                        message.images.forEach(img => {
                            attachedImages.push(img);
                            addImagePreview({ name: img.name }, img.data);
                        });
                    }
                    break;
            }
        });
        
        // 初始化
        vscode.postMessage({ command: 'ready' });
        
        setTimeout(() => {
            messageInput.focus();
        }, 100);
    </script>
</body>
</html>`;
}

function handleReviewMessage(text, attachments, triggerId, mcpIntegration) {
    const funnyResponses = [
        getLocalizedText('responses.sent1'),
        getLocalizedText('responses.sent2'),
        getLocalizedText('responses.sent3'),
        getLocalizedText('responses.sent4'),
        getLocalizedText('responses.sent5')
    ];
    
    console.log(`${mcpIntegration ? 'MCP响应' : '审核'} 已提交: ${text}`);
    
    if (chatPanel) {
        setTimeout(() => {
            const randomResponse = funnyResponses[Math.floor(Math.random() * funnyResponses.length)];
            
            chatPanel.webview.postMessage({
                command: 'addMessage',
                text: randomResponse,
                type: 'system'
            });
            
            // 发送响应后，保持输入框禁用状态，等待下一次MCP调用激活
            // 移除自动重新激活逻辑，只有新的MCP请求才能重新激活
            
        }, 500);
    }
}

function handleImageUpload() {
    vscode.window.showOpenDialog({
        canSelectMany: true,
        openLabel: '选择图片上传',
        filters: {
            '图片': ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp']
        }
    }).then(fileUris => {
        if (fileUris && fileUris.length > 0) {
            logMessage(`用户上传了 ${fileUris.length} 张图片`);
            
            const imagePromises = fileUris.map(async (uri) => {
                try {
                    const fileData = await vscode.workspace.fs.readFile(uri);
                    const fileName = path.basename(uri.fsPath);
                    const fileExtension = path.extname(fileName).toLowerCase();
                    
                    let mimeType = 'image/';
                    switch (fileExtension) {
                        case '.png': mimeType += 'png'; break;
                        case '.jpg':
                        case '.jpeg': mimeType += 'jpeg'; break;
                        case '.gif': mimeType += 'gif'; break;
                        case '.bmp': mimeType += 'bmp'; break;
                        case '.webp': mimeType += 'webp'; break;
                        default: mimeType += 'png';
                    }
                    
                    const base64Data = Buffer.from(fileData).toString('base64');
                    const dataUrl = `data:${mimeType};base64,${base64Data}`;
                    
                    return {
                        type: 'image',
                        name: fileName,
                        data: dataUrl,
                        size: fileData.length
                    };
                } catch (error) {
                    logMessage(`读取图片文件失败: ${error.message}`);
                    return null;
                }
            });
            
            Promise.all(imagePromises).then(images => {
                const validImages = images.filter(img => img !== null);
                if (validImages.length > 0 && chatPanel) {
                    chatPanel.webview.postMessage({
                        command: 'addImages',
                        images: validImages
                    });
                }
            });
        }
    });
}

function deactivate() {
    logMessage('Review Gate V3 IPC通信扩展正在停用...');
    
    // 停止IPC服务器
    if (ipcServer) {
        ipcServer.stop();
        ipcServer = null;
    }
    
    mcpReady = false;
    
    logMessage('✅ Review Gate V3 IPC通信扩展已完全停用');
}

module.exports = {
    activate,
    deactivate
}; 